<?php
require_once("inc.member.php");

$this_title="$vars[member_title] &raquo; ".($_GET["type"]=="add"? __("Add Sale") : __("View Sales"));
$content_title = $page_title=$_GET["type"]=="add"? __("Add Sale") : __("View Sales");
$list_file=$vars["file"]["member"]["sales_list"];

if(!in_array($_GET["type"], array("add","edit"))){
	header("location: $this_file?type=add");
	exit();
}

if($_GET["type"]=="edit"){
	if(!$get_s["id"]){
		$errmsg="No sale with that ID found!";
	}elseif(!@mysql_num_rows($r=mysql_query("select * from $db->purchase where (uid='$uid' or (creator='u' and cid='$uid')) and id='$get_d[id]'"))){
		$errmsg="No sale with that ID found!";
	}else{
		$r_sale=mysql_fetch_assoc($r);
		$user=$r_user;
	}
}

if($errmsg){
	$errmsg="<h2>$page_title</h2>".format_err($errmsg);

	print format_member_page($errmsg, $this_title, $content_title);
	exit();
}

$r_scat[0]="";
$r_scat_d[""]=__("All categories");
$cats=get_all_subcat_by_maincat();
for($i=0,$t=count($cats);$i<$t;$i++){
	$r_scat[($i+1)]=$cats[$i]["id"];
	$r_scat_d[$cats[$i]["id"]]=$cats[$i]["c"].$cats[$i]["title"];
}
$r_sale_point = $vars['dbv']['sale_point'];
$r_status=array("confirmed","cancelled");
$r_status_d=array("confirmed"=>__("Confirmed"),"cancelled"=>__("Cancelled"));
$r_payment = array('e','m','s');//$vars['dbv']['sale_payment'];
$r_payment_d = $vars['dbv']['sale_payment_d'];
//$r_payment_d['e'] .= ' - '.$vars['currency'].number_format($r_user['ewallet'], 2);
//$r_payment_d['m'] .= ' - '.$vars['currency'].number_format($r_user['swallet'], 2);
$r_collected=$vars['dbv']['sale_collected'];
$r_collected_d=$vars['dbv']['sale_collected_d'];
$r_purchase_from=array("hq");
$r_purchase_from_d = array('hq'=>__("Headquarter"));
$t=@mysql_num_rows($r=mysql_query("select * from $db->users where is_stockist='y' and status!='terminated' order by name"));
for($i=0;$i<$t;$i++){
	$this_stockist = mysql_fetch_assoc($r);
	$r_purchase_from[($i+1)] = $this_stockist['id'];
	$r_purchase_from_d[$this_stockist['id']] = $this_stockist['id']." - ".$this_stockist['name'];
}
$country_code=$vars['common']['country_code'];
$country_code_t=$vars['common']['country_code_text'];
foreach($country_code_t as $code=>$cname){
 $country_code_d[$code]=__($cname);
}
$country_code_d['']=__("All");

$td_width=180;
$datetime=ndate($vars["system_date_format"]);

require_once(M_ROOT."/classes/cls_search_cat_display.php");

//#####AJAX CALL#####
//search product
if($_GET["aj"] && $_GET["search_prod"]){
	$o_searchcat = new SearchCat($post_d['catid'], $product_title = $post_d['title'], $cur_page = $post_d['page'], $item_per_page = 10);
	print $o_searchcat->display();
	exit();
}

//calculate product cost
if($_GET["aj"] && $_GET["calc_cost"]){
	$output = ajax_calc_prod_cost($post_d, $post_s);
	print $output;
	exit();
}
if($_GET["aj"] && $_GET["check_uid"]){
	if(!$r_ref=get_user_detail_by_id($post_d['uid'])){
		$ajerrmsg="Member ID '$post_s[uid]' could not be found.";
	}elseif(!is_group_matrix_downline_of_which($post_d['uid'], $uid, 'ref') && !is_group_matrix_downline_of_which($post_d['uid'], $uid, 'matrix_upline')){
		$ajerrmsg="Member ID '$post_s[uid]' is not in your group.";
	}else{
		$ajmsg="Member ID: $post_s[uid], Name: $r_ref[name]";
	}
	$xml=array("status"=>($ajerrmsg? "2" : "1"), "msg"=>$ajmsg.$ajerrmsg);
	print format_xml($xml);
	exit();
}
//#####END AJAX CALL#####

//#####PRINT INVOICE#####
if($_GET['print_invoice']){
	$print_result = print_invoice($r_sale);
	
	print $print_result['css'].$print_result['invoice'];
	exit;
}

//#####ADD SALES POST#####
if($_SESSION["user_add_member_sale"] && $_POST["__req"]){
	//#####ERROR CHECK#####
	$chk_arr="_remark";
	$chk_arr=explode(",", $chk_arr);
	foreach($post_s as $f=>$v){
		if(in_array($f, $chk_arr)){
			$data[$f]=$v;
		}
	}
	$errmsg=verify_form_data("purchase", $data);
	if(!$errmsg){
		if($_GET["type"]=="add"){
			//check uid
			if($r_user['activated'] != 'y'){
				$errmsg.=__("You have not yet activated and you cannot place any order.")."<br />\n";
			}
			//check product entry
			$i=0;
			foreach($post_d as $f=>$v){
				if(preg_match('/^e_refno_/', $f)){
					$pi=preg_replace('/e_refno_/', '', $f);
					$prods[$i]["refno"]=$v;
					$prods[$i]["refno_s"]=$post_s["e_refno_$pi"];
					$prods[$i]["qty"]=$post_d["e_qty_$pi"];
					$i++;
				}
			}
			if(!count($prods)){
				$errmsg.=__("You must provide at least one product to add a sale.")."<br />\n";
			}else{
				$prod_dbr=explode("#", $vars["dbr"]["purchase_detail"]["qty"]);
				$all_prods=array();
				for($i=0,$t=count($prods);$i<$t;$i++){
					//check for duplicate
					if(in_array($prods[$i]["refno"], $all_prods)){
						$errmsg.=replace_tag(__("Some of the same product (reference no. '<%refno%>') has been entered more than once."), array("<%refno%>"=>$prods[$i]["refno_s"]))."<br />\n";
						$i=$t;
					}else{
						//check product key in / refno / qty
						if(!strlen($prods[$i]["refno"])){
							$errmsg.=replace_tag(__("Please provide a product reference no. in the product entry box #<%x%>."), array("<%x%>"=>strval($i+1)))."<br />\n";
						}else{
							$all_prods[]=$prods[$i]["refno"];
							$this_prod=@mysql_fetch_assoc(mysql_query("select * from $db->products where refno='".$prods[$i]["refno"]."' and status='active'")) or false;
							if(!$this_prod){
								$errmsg.=replace_tag(__("Product with reference no. '<%ref%>' could not be found."), array("<%ref%>"=>$prods[$i]["refno_s"]))."<br />\n";
							}else{
								$prods[$i]["id"]=$this_prod["id"];
								$prods[$i]["prod_type"]=$this_prod["prod_type"];
								//expanded_prods for use in recording product details in a sale, expanded_prods will store all the products entered, and will expand (store)
								//each of sub-products of a jump start package, with this sub-products is stored in an array within same record of expanded_prods[index]
								$expanded_prods[$i]["id"]=$this_prod["id"];
								$expanded_prods[$i]["refno"]=$prods[$i]["refno"];
								$expanded_prods[$i]["prod_type"]=mysql_real_escape_string($this_prod["prod_type"]);
								$expanded_prods[$i]["title"]=mysql_real_escape_string($this_prod["title"]);
								$expanded_prods[$i]["bv"]=calc_package_point("bv", $this_prod["id"]);
								$expanded_prods[$i]["dp"]=calc_package_point("dp", $this_prod["id"]);
								$expanded_prods[$i]["rp"]=calc_package_point("rp", $this_prod["id"]);
								$expanded_prods[$i]["req_qty"]=$prods[$i]["qty"];
								//prods_info store all the product info, with index is the product refno
								$prods_info[$prods[$i]["refno"]]=$expanded_prods[$i];
								if($this_prod["prod_type"]=='n'){
									//update_prod_qty used below to deduct product quantity
									$update_prod_qty[$prods[$i]["refno"]]["id"]=$prods[$i]["id"];
									$update_prod_qty[$prods[$i]["refno"]]["req_qty"]+=$prods[$i]["qty"];
									$update_prod_qty[$prods[$i]["refno"]]["avai_qty"]=$this_prod["qty"];
									$update_prod_qty[$prods[$i]["refno"]]["qty_type"]=$this_prod["qty_type"];
								}elseif($this_prod["prod_type"]=='p'){
									//package-> the product within the package can be 'inactive', but cannot be absent
									$t2=@mysql_num_rows($r2=mysql_query("select j.refno from $db->package_detail j where j.pkid='$this_prod[id]' and j.pid not in (select id from $db->products where status!='deleted')"));
									if($t2 > 0){
										$nepid="";
										for($j=0;$j<$t2;$j++){
											$nepid.=($nepid? ", ": "").mysql_result($r2, $j);
										}
										$errmsg.=replace_tag(__("Some of the product(s) within the package with reference no. '<%refno%>' is not available, product(s) that is no longer available is listed below:"), array("<%refno%>"=>$this_prod["refno"]))."<br />\n<br />\n".__("Product").__(":")." $nepid<br />\n";
									}else{
										$t2=@mysql_num_rows($r2=mysql_query("select p.*, p.qty as avai_qty, j.qty as req_qty from $db->products p, $db->package_detail j where j.pkid='$this_prod[id]' and j.pid=p.id"));
										for($j=0;$j<$t2;$j++){
											$this_pck=mysql_fetch_assoc($r2);
											$expanded_prods[$i]["pck_prod"][$j]["id"]=$this_pck["id"];
											$expanded_prods[$i]["pck_prod"][$j]["refno"]=mysql_real_escape_string($this_pck["refno"]);
											$expanded_prods[$i]["pck_prod"][$j]["prod_type"]=mysql_real_escape_string($this_pck["prod_type"]);
											$expanded_prods[$i]["pck_prod"][$j]["title"]=mysql_real_escape_string($this_pck["title"]);
											$expanded_prods[$i]["pck_prod"][$j]["bv"]=$this_pck["bv"];
											$expanded_prods[$i]["pck_prod"][$j]["dp"]=$this_pck["dp"];
											$expanded_prods[$i]["pck_prod"][$j]["rp"]=$this_pck["rp"];
											$expanded_prods[$i]["pck_prod"][$j]["req_qty"]=$this_pck["req_qty"];
											$prods_info[mysql_real_escape_string($this_pck["refno"])]=$expanded_prods[$i]["pck_prod"][$j];
											$update_prod_qty[mysql_real_escape_string($this_pck["refno"])]["id"]=$this_pck["id"];
											$update_prod_qty[mysql_real_escape_string($this_pck["refno"])]["req_qty"]+=$this_pck["req_qty"]*$prods[$i]["qty"];
											$update_prod_qty[mysql_real_escape_string($this_pck["refno"])]["avai_qty"]=$this_pck["avai_qty"];
											$update_prod_qty[mysql_real_escape_string($this_pck["refno"])]["qty_type"]=$this_pck["qty_type"];
										}
									}
								}
							}
							if(!strlen($prods[$i]["qty"])){
								$errmsg.=replace_tag(__("Please provide a quantity for the product with reference no. '<%ref%>'."), array("<%ref%>"=>$prods[$i]["refno_s"]))."<br />\n";
							}elseif(!is_numeric($prods[$i]["qty"]) || $prods[$i]["qty"]<=0){
								$errmsg.=replace_tag(__("Please provide a valid quantity (numerical with value more than zero) for the product with reference no. '<%ref%>'."), array("<%ref%>"=>$prods[$i]["refno_s"]))."<br />\n";
							}elseif($prods[$i]["qty"] > $prod_dbr[6]){
								$errmsg.=replace_tag(__("Please provide a quantity in the range <%from%> to <%to%> for the product with reference no. '<%ref%>', you have provided <%x%>."), array("<%ref%>"=>$prods[$i]["refno_s"], "<%from%>"=>"1", "<%to%>"=>strval($prod_dbr[6]), "<%x%>"=>$prods[$i]["qty"]))."<br />\n";
							}
						}
					}
				}
				//check sufficient quantity in bulk
				if(!$errmsg){
					if(in_array($post_s["purchase_from"], array("hq","cr"))){
						if(($result=check_sufficient_qty($prods))!==true){
							$errmsg.=$result;
						}
					}elseif($post_s["purchase_from"] && stockist_sid_found($post_d["purchase_from"])){
						$this_stockist = get_stockist_detail_by_sid($post_d['purchase_from']);
						if(($result=check_sufficient_stockist_qty($this_stockist["id"], $prods))!==true){
							if($result===false){
								$errmsg.=__("The stockist could not be found.")."<br />\n";
							}else{
								$errmsg.=$result;
							}
						}
					}
				}
			}
			//check pickup location
			if(!in_array($post_s["purchase_from"], $r_purchase_from)){
				$errmsg.=__("Please select a pickup location.")."<br />\n";
			}elseif(!in_array($post_s["purchase_from"], array("hq","cr"))){
				if(!$post_s["purchase_from"]){
					$errmsg.=__("Please select a stockist for the pickup location.")."<br />\n";
				}elseif(!$r_stockist=get_stockist_detail_by_sid($post_d["purchase_from"])){
					$errmsg.=replace_tag(__("The Stockist ID: '<%sid%>' could not be found."), array("<%sid%>"=>$post_h["purchase_from"]))."<br />\n";
				}
			}
			//check payment type
			if(!in_array($post_s["payment_channel"], $r_payment)){
				$errmsg.=__("Please select a payment channel.")."<br />\n";
			}
		}
	}
	//check uid existence
	if(!$errmsg){
		if(!$post_s['uid']){
			$errmsg .= __("Please provide a Member ID.")."<br />";
		}elseif(!$user = get_user_detail_by_id($post_d['uid'])){
			$errmsg .= replace_tag(__("The Member ID '<%uid%>' could not be found."), array('<%uid%>'=>$post_h['uid']))."<br />";
		}elseif($post_s['uid'] != $uid && $post_s['payment_channel'] == 'm'){
			$errmsg .= replace_tag(__("You cannot use <%title%> for purchase for other member."), array('<%title%>'=>$vars['swallet_title']))."<br />";
		}
	}
	//check if member have enough ewallet
	if(!$errmsg){
		foreach($r_sale_point as $point_type){
			$sale_point[$point_type] = calc_prod_point($point_type, $prods);
		}
		if($post_s['payment_channel'] == 'e'){
			$pwallet = 'ewallet';
		}elseif($post_s['payment_channel'] == 'm'){
			$pwallet = 'swallet';
		}elseif($post_s['payment_channel'] == 's'){
			$pwallet = 'eswallet';
		}
		if($_GET["type"]=="add" && in_array($post_s["payment_channel"], array("e","m","s"))){			
			if($pwallet == 'eswallet') $deduct_amount = $sale_point['bv'];			
			else $deduct_amount = $sale_point['dp'];
		
			if($r_user[$pwallet] < $deduct_amount + $post_s['delivery_cost']){
				$errmsg.=replace_tag(__("You do not have sufficient <%title%> for this sale."), array("<%title%>"=>__($vars[$pwallet."_title"])))."<br />\n<br />\n".replace_tag(__("Required <%title%>:"), array("<%title%>"=>__($vars[$pwallet."_title"])))." ".number_format($deduct_amount + $post_s['delivery_cost'], 2)."<br />\n".replace_tag(__("Available <%title%>:"), array("<%title%>"=>__($vars[$pwallet."_title"])))." ".number_format($r_user[$pwallet], 2)."<br />\n";
			}
		}
	}
	//#####END ERROR CHECK#####

	//#####PREVIEW OR CONFIRM#####
	$preview = $confirm = false;
	if(!$errmsg){
		if($_GET["type"]=="add"){
			if(!$post_s["__confirm"] && !$post_s['__edit']){
				$__preview = true;
			}elseif($post_s["__confirm"]){
				$__confirm = true;
			}
		}else{
			$__confirm = true;
		}
	}

	//#####ADD TO DB#####
	if(!$errmsg && $__confirm){
		if($_GET["type"]=="add"){//add
			$stockist_sale= in_array($post_s["purchase_from"], array('hq','cr'))? "n" : "y";
			if(!in_array($post_s["purchase_from"], array('hq','cr'))){
				$collect_address=mysql_real_escape_string($r_stockist["address"].($r_stockist["address2"]? ", $r_stockist[address2]" : ""));
				$collect_city=mysql_real_escape_string($r_stockist['city']);
				$collect_zip=mysql_real_escape_string($r_stockist['zip']);
				$collect_state=mysql_real_escape_string($r_stockist['state']);
				$collect_country=mysql_real_escape_string($r_stockist['country']);
				$sid = $r_stockist['id'];
			}else{
				$sid = '';
			}
			if($post_s["sale_collected"]=='y'){
				$collected_date=strlen($post_s["_collected_date"])? $post_d["_collected_date"] : $datetime;
			}
			
			//deduct member ewallet
			if(in_array($post_s["payment_channel"], array('e','m','s'))){
				$ew_updated=false;
				if(!mysql_query($sql="update $db->users set $pwallet=$pwallet-".($deduct_amount + $post_s['delivery_cost'])." where id='$uid' limit 1")){
					$ew_errmsg=replace_tag(__("Error updating your <%title%> account, please contact us."), array("<%title%>"=>__($vars[$pwallet."_title"])))."<br />\n".($vars['debug']? "<br />\nSQL: $sql<br />\n<br />\nError: ".mysql_error()."<br />\n" : "");
					$ew_errlog="Error updating the member {$vars[$pwallet."_title"]} account while member place a sale order, please manually update this member {$vars[$pwallet."_title"]} account by executing SQL.\n\nSQL: $sql\n\nError: ".mysql_error()."\n";
				}else{
					$ew_updated=true;
				}
			}
			
			//previous sales bv, before adding sales, to calculate new rank later
			$old_bv = @mysql_result($r=mysql_query("select sum(total_bv) from $db->purchase where uid='$post_d[uid]' and first_sale='y' and no_bv!='y' and status='confirmed'"), 0) or 0;
			
			//create sale record
			$sql="insert into $db->purchase (creator, cid, uid, member_sale, first_sale, no_bv, stockist_sale, sid, collect_address, collect_city, collect_zip, collect_state, collect_country, total_bv, total_dp, total_rp, delivery_cost, payment_type, collected, status, remark, cdate, edate)
			values ('u', '$uid', '$post_d[uid]', 'y', 'y', '".($post_s['payment_channel'] == 'm'? 'y' : 'n')."', '$stockist_sale', '$sid', '$collect_address', '$collect_city', '$collect_zip', '$collect_state', '$collect_country', '$sale_point[bv]', '".$sale_point['dp']."', '".$sale_point['rp']."', '$post_d[delivery_cost]', '$post_d[payment_channel]', 'n', 'confirmed', '$post_d[_remark]', '$datetime', '$datetime')";
			if(!mysql_query($sql)){
				$sale_errmsg.=__("Error creating the sale. Please contact us.")."<br />\n".($vars['debug']? "<br />\nSQL: $sql<br />\n<br />\nError: ".mysql_error()."<br />\n" : "");
				$sale_errlog.="Error creating a new member sale while member place a sale order. Please manually create this sale by executing SQL.<br />\n<br />\nSQL: $sql\n\nError: ".mysql_error()."\n";
			}else{
				$new_sid=mysql_insert_id();
				$sale_refno = $refno = "MS" . str_pad($new_sid, $vars['refno_min_digit'], '0', STR_PAD_LEFT);
				if(!mysql_query($sql="update $db->purchase set refno='$refno' where id='$new_sid' limit 1")){
					$sale_errmsg.=__("Error recording the sale reference number. Please contact us.")."<br />\n".($vars['debug']? "<br />\nSQL: $sql<br />\n<br />\nError: ".mysql_error()."<br />\n" : "");
					$sale_errlog.="Error recording the sale reference number while member place a sale order. Please manually record the sale reference number by executing SQL.<br />\n<br />\nSQL: $sql\n\nError: ".mysql_error()."\n";
				}
				$sale_refno = $refno = $new_sid;//refno is not used yet

				//insert product details
				for($i=0,$t=count($expanded_prods);$i<$t;$i++){
					$package=$expanded_prods[$i]["prod_type"]=='p'? true : false;
					if(!mysql_query($sql="insert into $db->purchase_detail (slid, pid, prod_type, refno, title, bv, dp, rp, qty) 
					values ('$new_sid', '".$expanded_prods[$i]["id"]."', '".$expanded_prods[$i]["prod_type"]."', '".$expanded_prods[$i]["refno"]."', '".$expanded_prods[$i]["title"]."', '".$expanded_prods[$i]["bv"]."', '".$expanded_prods[$i]["dp"]."', '".$expanded_prods[$i]["rp"]."', '".$expanded_prods[$i]["req_qty"]."')")){
						$prod_detail_errmsg.=replace_tag(__("Product reference no. '<%refno%>'."), array("<%refno%>"=>StripSlashes($expanded_prods[$i]["refno"])))."<br />\nSQL: $sql<br />\nError: ".mysql_error()."<br />\n";
						$prod_detail_errlog.=replace_tag("Product reference no. '<%refno%>'.", array("<%refno%>"=>StripSlashes($expanded_prods[$i]["refno"])))."\nSQL: $sql\nError: ".mysql_error()."\n";
					}
					//insert each products detail in a package
					if($package){
						for($j=0,$t2=count($expanded_prods[$i]["pck_prod"]);$j<$t2;$j++){
							if(!mysql_query($sql="insert into $db->purchase_detail (slid, pid, pkid, prod_type, refno, title, bv, dp, rp, qty) 
							values ('$new_sid', '".$expanded_prods[$i]["pck_prod"][$j]["id"]."', '".$expanded_prods[$i]["id"]."', 'n', '".$expanded_prods[$i]["pck_prod"][$j]["refno"]."', '".$expanded_prods[$i]["pck_prod"][$j]["title"]."', '".$expanded_prods[$i]["pck_prod"][$j]["bv"]."', '".$expanded_prods[$i]["pck_prod"][$j]["dp"]."', '".$expanded_prods[$i]["pck_prod"][$j]["rp"]."', '".$expanded_prods[$i]["pck_prod"][$j]["req_qty"]."')")){
								$prod_detail_errmsg.=replace_tag(__("Product reference no. '<%refno%>' of a package with reference no. '<%pck_refno%>'."), array("<%refno%>"=>StripSlashes($expanded_prods[$i]["pck_prod"][$j]["refno"]), "<%pck_refno%>"=>StripSlashes($expanded_prods[$i]["refno"])))."<br />\nSQL: $sql<br />\nError: ".mysql_error()."<br />\n";
								$prod_detail_errlog.=replace_tag("Product reference no. '<%refno%>' of a package with reference no. '<%pck_refno%>'.", array("<%refno%>"=>StripSlashes($expanded_prods[$i]["pck_prod"][$j]["refno"]), "<%pck_refno%>"=>StripSlashes($expanded_prods[$i]["refno"])))."\nSQL: $sql\nError: ".mysql_error()."\n";
							}
						}
					}
				}

				//calculate bonus
				$bonus_result = calc_sponsor_bonus($new_sid);
				if(!$bonus_result['status']){
					$bonus_errmsg = $bonus_errlog = $bonus['errmsg'];
				}
				
				//recalculate user new rank
				$new_rank = calc_rank($post_d['uid'], $old_bv);
				if($new_rank != $user['rank_a']){
					$sql = "update $db->users set rank_a='$new_rank' where id='$post_d[uid]' limit 1";
					if(!mysql_query($sql)){
						$rank_errmsg.=__("Error updating the member rank, please manually update the member rank by executing SQL.")."<br /><br />SQL: $sql<br /><br />".mysql_error()."<br />";
						$rank_errlog.="Error updating the member rank while member ID#$uid purchase sales for member ID#$post_s[uid], please manually update the member rank by executing SQL.\n\nSQL: $sql\n\n".mysql_error()."\n";
					}
				}

				//email user
				$dprods=prepare_prod_for_display($prods);
				$formatted_prod=format_prod_display($dprods, $post_s['delivery_cost']);
				if($post_s["purchase_from"]=='hq'){
					$location = __("Headquater");
				}elseif($post_s["purchase_from"]=='cr'){
					$location = __("Courier");
				}else{
					$location = __("Stockist ID").__(":")." $post_h[purchase_from], ".__("Name").__(":")." ".$r_stockist["name"]."<br />\n$r_stockist[address]".($r_stockist["address2"]? ", ".$r_stockist["address2"] : "").($r_stockist['city']? "<br />\n$r_stockist[city]" : '').($r_stockist['zip']? "<br />\n$r_stockist[zip], " : '').($r_stockist['state']? "$r_stockist[state]" : '')."<br />\n".$country_code_d[$r_stockist["country"]];
				}
				$td_style="style='border:1px solid black; padding: 3px;'";
				$sales_info="
				<table style='width:600px; border-collapse: collapse; font-family:arial; font-size:12px;'>
					<tr>
						<td $td_style>".__("Member ID").__(":")."</td>
						<td $td_style>$user[code]</td>
					</tr>
					<tr>
						<td $td_style>".__("Name").__(":")."</td>
						<td $td_style>$user[name]</td>
					</tr>
					<tr>
						<td $td_style>".__("Date").__(":")."</td>
						<td $td_style>".date($vars["date_format"], strtotime($datetime))."</td>
					</tr>
					<tr>
						<td $td_style>".__("Order Total").__(":")."</td>
						<td $td_style>".number_format($sale_point['bv'], 2)." BV</td>
					</tr>
					<tr>
						<td $td_style>".__("Payment Type").__(":")."</td>
						<td $td_style>".$r_payment_d[$post_s["payment_channel"]].($uid != $post_s['uid']? " by Member ID#$uid" : '')."</td>
					</tr>
				</table>";
				$u_sub=$vars["title"]." - ".__("Sales Created");
				$u_msg="
				<p>Dear $user[_name],</p>
				<p>You had just placed a sale with us at $vars[title], details below:</p>
				$sales_info<br />\n<br />\n
				".__("Order Details:")."<br />\n<br />\n
				$formatted_prod";
				if($user['_email']){
					email_user($user["_email"], $u_sub, $u_msg);
				}

				//email admin
				$a_sub=$vars["title"]." - ".__("Sales Created");
				$a_msg="
				<p>Dear admin,</p>
				<p>A member had just placed a sale with us at $vars[title], details below:</p>
				$sales_info<br />\n<br />\n
				".__("Order Details:")."<br />\n<br />\n
				$formatted_prod";
				email_admin($a_sub, $a_msg);
			}
			
			//update product qty
			if(count($update_prod_qty)){
				if(in_array($post_s["purchase_from"], array("hq","cr"))){
					//update main inventory
					foreach($update_prod_qty as $refno => $detail){
						//only update product with quantity not = unlimited
						if($detail["qty_type"] == 'l'){//l - limited
							if(!mysql_query($qty_sql="update $db->products set qty=qty-".$detail["req_qty"]." where refno='$refno'")){
								$qty_errmsg.=replace_tag(__("Product reference no. '<%refno%>', quantity to deduct: <%x%>."), array("<%refno%>"=>StripSlashes($refno), "<%x%>"=>strval($qty)))."<br />\nSQL: $qty_sql<br />";
								$qty_errlog.=replace_tag("Product reference no. '<%refno%>', quantity to deduct: <%x%>.", array("<%refno%>"=>StripSlashes($refno), "<%x%>"=>strval($qty)))."\nSQL: $qty_sql\n";
							}
						}
						//create qty record
						if(!mysql_query($sql="insert into $db->prod_qty_record (pid, sid, ttype, type, qty, cdate) values ('$detail[id]', '$new_sid', 'm', 'd', '$detail[req_qty]', '$datetime')")){
							$qty_rec_errmsg.=replace_tag(__("Product reference no. '<%refno%>', quantity record to add:"), array("<%refno%>"=>StripSlashes($refno)))."<br />\nSQL: $sql<br />";
							$qty_rec_errlog.=replace_tag("Product reference no. '<%refno%>', quantity record to add:", array("<%refno%>"=>StripSlashes($refno)))."\nSQL: $sql\n";
						}
					}
				}else{
					//update stockist inventory
					foreach($update_prod_qty as $refno => $detail){
						if(!mysql_query($qty_sql="update $db->stockist_inventory set qty=qty-".$detail["req_qty"]." where sid='$r_stockist[id]' and refno='$refno'")){
							$qty_errmsg.=replace_tag(__("Product reference no. '<%refno%>', stockist quantity to deduct: <%x%>."), array("<%refno%>"=>StripSlashes($refno), "<%x%>"=>strval($qty)))."<br />\nSQL: $qty_sql<br />";
							$qty_errlog.=replace_tag("Product reference no. '<%refno%>', stockist quantity to deduct: <%x%>.", array("<%refno%>"=>StripSlashes($refno), "<%x%>"=>strval($qty)))."\nSQL: $qty_sql\n";
						}
						//create stockist qty record
						if(!mysql_query($sql="insert into $db->stck_prod_qty_record (pid, slid, sid, ttype, type, qty, cdate) values ('$detail[id]', '$new_sid', '$r_stockist[id]', 'm', 'd', '$detail[req_qty]', '$datetime')")){
							$qty_rec_errlog.=replace_tag("Product reference no. '<%refno%>', quantity record to add:", array("<%refno%>"=>StripSlashes($refno)))."\nSQL: $sql\n";
						}
					}
				}
			}
			if($qty_errmsg){
				$qty_errmsg=__("Error updating the product quantity.")." ".($post_s["purchase_from"]=="hq"? __("Please manually deduct the respective quantity for each of the product(s) below by executing SQL:") : replace_tag(__("Please manually deduct the respective quantity for each of the product(s) to this stockist ID <%sid%> by executing SQL, as below:"), array("<%sid%>"=>$r_stockist["sid"])))."<br />\n<br />\n$qty_errmsg<br />\n";
				$qty_errlog="Error updating the product quantity.".($post_s["purchase_from"]=="hq"? "Please manually deduct the respective quantity for each of the product(s) below by executing SQL:" : replace_tag("Please manually deduct the respective quantity for each of the product(s) to this stockist ID <%sid%> by executing SQL, as below:", array("<%sid%>"=>$r_stockist["sid"])))."\n\n$qty_errlog\n";
				$critical_error.=$qty_errlog;
			}
			if($qty_rec_errmsg){
				$qty_rec_errmsg=__("Error recording the product quantity transaction.")." ".($post_s["purchase_from"]=="hq"? __("Please manually add the quantity record below by executing SQL:") : replace_tag(__("Please manually add the quantity record for this stockist ID <%sid%> by executing SQL, as below:"), array("<%sid%>"=>$r_stockist["sid"])))."<br />\n<br />\n$qty_rec_errmsg<br />\n";
				$qty_rec_errlog="Error recording the product quantity transaction.".($post_s["purchase_from"]=="hq"? "Please manually add the quantity record below by executing SQL:" : replace_tag("Please manually add the quantity record for this stockist ID <%sid%> by executing SQL, as below:", array("<%sid%>"=>$r_stockist["sid"])))."\n\n$qty_rec_errlog\n";
				$critical_error.=$qty_rec_errlog;
			}
			
			//record ewallet transaction
			if(in_array($post_s["payment_channel"], array('e','m','s'))){
				$descr = addslashes("Debited $vars[currency]".number_format($deduct_amount + $post_s['delivery_cost'], 2)." for the sale with ID #$sale_refno".($uid != $post_s['uid']? " (for member ID#$post_s[uid])" : ''));
				if(!mysql_query($sql="insert into {$vars['dbi']['prefix']}member_".$pwallet."_record (uid, type, amount, descr, cdate) values ('$uid', 'debit', '".($deduct_amount + $post_s['delivery_cost'])."', '$descr', '$datetime')")){
					$ewrec_errmsg.=replace_tag(__("Error creating the <%title%> record for this sale transaction. Please manually create this transaction by executing SQL."), array("<%title%>"=>__($vars[$pwallet.'_title'])))."<br /><br />SQL: $sql<br /><br />Error: ".mysql_error()."<br />";
					$ewrec_errlog.=replace_tag("Error creating the <%title%> record for this sale transaction. Please manually create this transaction by executing SQL.", array("<%title%>"=>__($vars[$pwallet.'_title'])))."\n\nSQL: $sql\n\nError: ".mysql_error()."\n";
				}else{
					$new_eid = mysql_insert_id();
					$refno = strtoupper(substr($pwallet, 0, 2))."D" . str_pad($new_eid, $vars['refno_min_digit'], '0', STR_PAD_LEFT);
					$last_bal = @mysql_result(mysql_query("select bal from {$vars['dbi']['prefix']}member_".$pwallet."_record where uid='$uid' and id!=$new_eid order by id desc limit 1"), 0);
					if(!$last_bal){
						$last_bal = 0;
					}
					$last_bal -= ($deduct_amount + $post_s['delivery_cost']);
					mysql_query("update {$vars['dbi']['prefix']}member_".$pwallet."_record set bal='$last_bal' where id='$new_eid' limit 1");
				}
			}
			
			//sale error message
			$msg=replace_tag(__("The new sale has been successfully created. The ID for this sale is <%id%>. The sale details are listed below."), array("<%id%>"=>"<span class='red bold'>$sale_refno</span>"))."<br />\n";
			$logstr="The new sale has been successfully created. The ID for this sale is $sale_refno (#$new_sid).";
			$excluded_fields = array('id','nm_name','nm_contact','actual_bv','actual_dp','actual_rp');
			$log_arr = mysql_fetch_assoc(mysql_query("select * from $db->purchase where id='$new_sid'"));
			if($log_arr){
				foreach($log_arr as $f => $v){
					if(!in_array($f, $excluded_fields)){
						$dbr = explode('#', $vars['dbr']['purchase'][$f]);
						$log_fields .= ($dbr[4]? $dbr[4] : $f)." = ".$v."\n";
					}
				}
				$log_fields = rtrim($log_fields, "\n");
			}
			$logstr .= "\n".$log_fields;
			if($qty_errmsg || $qty_rec_errmsg || $sale_errmsg || $prod_detail_errmsg || $rank_errmsg || $bonus_errmsg || $ew_errmsg || $ewrec_errmsg){
				$msg.=($vars['debug']? "<br />\n<span class='red'>".__("However, some error(s) had occurred:")."<br />\n".
				($qty_errmsg? "<br />\n$qty_errmsg<br />\n" : "").
				($qty_rec_errmsg? "<br />\n$qty_rec_errmsg<br />\n" : "").
				($sale_errmsg? "<br />\n$sale_errmsg<br />\n" : "").
				($prod_detail_errmsg? "<br />\n".__("Some of the product(s) could not be properly linked with this sale. Please execute the respective SQL to properly insert the link, as below:")."<br />$prod_detail_errmsg<br />\n" : "").
				($ew_errmsg? "<br />\n$ew_errmsg<br />\n" : "").
				($rank_errmsg? "<br />\n$rank_errmsg<br />\n" : "").
				($bonus_errmsg? "<br />\n$bonus_errmsg<br />\n" : "").
				($ewrec_errmsg? "<br />\n$ewrec_errmsg<br />\n" : "") : '');
				
				$critical_error="$logstr\nHowever, some error(s) had occurred:\n".
				($qty_errlog? "\n$qty_errlog\n" : "").
				($qty_rec_errlog? "\n$qty_rec_errlog\n" : "").
				($sale_errlog? "\n$sale_errlog\n" : "").
				($prod_detail_errlog? "\nSome of the product(s) could not be properly linked with this sale. Please execute the respective SQL to properly insert the link, as below:\n$prod_detail_errlog\n" : "").
				($ew_errlog? "\n$ew_errlog\n" : "").
				($rank_errlog? "\n$rank_errlog\n" : "").
				($bonus_errlog? "\n$bonus_errlog\n" : "").
				($ewrec_errlog? "\n$ewrec_errlog\n" : "");
				$logstr = '';
			}
		}
	}

	//log critical error
	if($critical_error || $logstr){
		$log_code=$_GET["type"]=="add"? "u-usa" : "u-use";
		$affected_uid=$_GET["type"]=="add"? $user['id'] : $r_sale["uid"];
		$extra_fields = array('slid'=>$get_s['type'] == 'add'? $new_sid : $r_sale['id']);
		if($critical_error){
			log_activity('e', 'u', $aid, 'u', $affected_uid, $log_code, $critical_error, $extra_fields);
		}elseif($logstr){
			$log_descr = $logstr;
			log_activity('a', 'u', $aid, 'u', $affected_uid, $log_code, $log_descr, $extra_fields);
		}
	}

	$msg=$msg? format_msg($msg) : "";
	$errmsg=$errmsg? format_err("There is some error(s), please correct them before continuing:<br />\n<br />\n$errmsg") : "";

	//stop after successful add
	if($_GET["type"] == 'add' && $msg){
		//set session to disallow re-submit
		$_SESSION["user_add_member_sale"] = false;
		$sales_info = str_replace('width:600px', 'width:100%', $sales_info);
		$formatted_prod = str_replace('width:600px', 'width:100%', $formatted_prod);
		$msg = "<div style='width:100%;'>$msg</div>";
		$msg.="<p>".__("The sale information is listed below.")."</p>
		$sales_info<br />\n<br />\n
		".__("Order Details:")."<br />\n<br />\n
		$formatted_prod
		<p class='center'><input type='button' value=\"".__("Add New Sale")."\" onclick=\"window.location='$this_file?type=add';\">
			<input type='button' value=\"".__("Back to Sale List")."\" onclick=\"window.location='$list_file';\">
			<input type='button' name='print_invoice' value=\"".__("Print Invoice")."\" /></p>";
		//javascript
		ob_start();
		?>
<script type="text/javascript" src="<?php echo JS_URL."/get_file_gzip.php?file=".urlencode("jquery.js"); ?>"></script>
<script type="text/javascript">
jQuery(document).ready(function(j){
	j('input[@name=print_invoice]').click(function(){
		window.open('<?php echo addslashes("$this_file?print_invoice=1&type=edit&id=$sale_refno"); ?>', 'print_window', 'status=1, toolbar=1, location=1, menubar=1, width=700, height=700');
	});
});
</script>
		<?php
		$jvscript = ob_get_clean();
		print format_member_page("<h2>$page_title</h2>".$msg, $this_title, $content_title, $jvscript);
		exit();
	}
}
//enable submission, only block for back button / refresh after successful add
$_SESSION["user_add_member_sale"] = true;
//#####END MEMBER SALES POST#####

$form_fields=array("uid"=>$uid,"sid"=>"","payment_channel"=>"e","_collected_date"=>ndate('Y-m-d'),"cdate"=>ndate('Y-m-d'),"edate"=>ndate('Y-m-d'),"status"=>"active","_remark"=>"");
foreach($form_fields as $field => $default){
	$db_fieldname=preg_match('/^_/', $field)? substr($field, 1) : $field;
	$dis[$field]=(!$post_s["__req"]? ($_GET["type"]=="edit"? $r_sale[$db_fieldname] : $default) : $post_h[$field]);
}
$dis["payment_channel"]=$_GET["type"]=="edit"? $r_sale["payment_type"] : $dis["payment_channel"];
$dis["collected"]=$_GET["type"]=="edit" && $r_sale["status"]=="cancelled"? $r_sale["collected"] : $dis["collected"];
$dis["_collected_date"]=$_GET["type"]=="edit" && !$post_s['__req'] && $r_sale["collected"]=="n" && $r_sale["collected_date"]=="0000-00-00 00:00:00"? "" : date('Y-m-d', strtotime($dis["_collected_date"]));
$dis["cdate"]=$_GET["type"]=="edit"? date($vars['date_format_short'], strtotime($dis["cdate"])) : $dis['cdate'];
$dis["edate"]=$_GET["type"]=="edit"? date($vars['date_format'], strtotime($dis["edate"])) : $dis['edate'];

if($dis["uid"]){
	if($user=get_user_detail_by_id($dis["uid"])){
		$user_text=__("Member ID").__(":")." ".$user["code"].__(",")." ".__("Name").__(":")." ".$user["name"];
		$user_preview_text=__(",")." ".__("Name").__(":")." ".$user["name"];
	}
}

//-----------------------------------PREVIEW------------------------------------
if($__preview){
	foreach($post_h as $p => $v){
		$form_inputfields.="<input type='hidden' name='$p' value=\"$v\" />\n";
	}

	//javascript
	ob_start();
	?>
<script type="text/javascript" src="<?php echo JS_URL."/get_file_gzip.php?file=".urlencode("jquery.js"); ?>"></script>
<script type="text/javascript">
	jQuery(document).ready(function(j){
		j('input[@name=edit_btn]').click(function(){
			j('input[@name=__confirm]').val('');
			j('input[@name=__edit]').val('1');
			j('input[@name=back_btn],input[@name=edit_btn],input[@name=submit_btn]').attr('disabled','disabled');
			j('form[@name=sale_form]').submit();
		});

		j('form[@name=sale_form]').submit(function(){
			j('input[@name=back_btn],input[@name=edit_btn],input[@name=submit_btn]').attr('disabled','disabled');
		});
	});
</script>
	<?php
	$jvscript = ob_get_clean();


	//format input row
	$display_fields=array("uid","_remark");
	foreach($form_fields as $field => $default){
		if(in_array($field, $display_fields)){
			$db_fieldname=preg_match('/^_/', $field)? substr($field, 1) : $field;
			$dbr=explode("#", $vars["dbr"]["purchase"][$db_fieldname]);
			$readonly=$textarea=false;
			$extra_display='';
			$form_inputfield[$db_fieldname]="
			<tr id='".$db_fieldname."_inputrow'>
				<td width='$td_width'>".__($dbr[4]).__(":").($dbr[3]=='m'? " ".__("*") : "")."</td>
				<td>".($db_fieldname == 'remark'? nl2br($dis[$field]) : $dis[$field]).$extra_display."</td>
			</tr>";
		}
	}

	//product entry row
	$i=0;
	foreach($post_d as $f=>$v){
		if(preg_match('/^e_refno_/', $f)){
			$pi=preg_replace('/e_refno_/', '', $f);
			$e_prods[$i]["refno"]=$v;
			$e_prods[$i]["qty"]=$post_d["e_qty_$pi"];
			$i++;
		}
	}
	$dprods=prepare_prod_for_display($e_prods);
	$formatted_prod=format_prod_display($dprods, $post_s['delivery_cost']);
	$formatted_prod = str_replace('width:600px;', 'width:100%;', $formatted_prod);
	$prod_entry_row="
	<tr>
		<td colspan='2'>".__("Products").__(":")."</td>
	</tr>
	<tr>
		<td colspan='2'>$formatted_prod</td>
	</tr>";
	
	$member_sales=
	"<form name='sale_form' method='post' action='$this_file?$_SERVER[QUERY_STRING]'>
	$form_inputfields
	<input type='hidden' name='__edit' />
	<input type='hidden' name='__confirm' value='1' />
	<table class='pbt_table preview_table' style='width:100%'>
		<tr class='pbt_header'>
			<td colspan='2'>".__("Sales Information")."</td>
		</tr>
		$form_inputfield[uid]
		$prod_entry_row
		$purchase_from_row
		<tr>
			<td>".__("Payment Type").__(":")."</td>
			<td>".$r_payment_d[$post_s["payment_channel"]]."</td>
		</tr>
		$form_inputfield[remark]
	</table>
	<table class='pbt_table' style='width:100%'>
		<tr>
			<td colspan='2' class='center' style='padding:20px 0 20px 0;'>
			<input type='button' value='".__("Back")."' name='back_btn' onclick=\"location='$post_[back_url]';\">&nbsp;&nbsp;&nbsp;
			<input type='button' value='".__("Edit Sales")."' name='edit_btn' />&nbsp;&nbsp;&nbsp;
			<input type='submit' name='submit_btn' value=\"".($_GET["type"]=="edit"? __("Update Sale") : __("Confirm Sale"))."\" />
			</td>
		</tr>
	</table>
	</form>";

//-----------------------------FIRST TIME / EDITING-----------------------------
}else{
	$payment_channel_select=$_GET["type"]=="edit"? $r_payment_d[$dis["payment_channel"]] : build_select($r_payment, $r_payment_d, $dis["payment_channel"], "payment_channel", $inputbox_style);
	$purchase_from_select = build_select($r_purchase_from, $r_purchase_from_d, $dis['purchase_from'], 'purchase_from', $inputbox_style);
	$collected_select=$_GET["type"]=="edit"? $r_collected_d[$dis["collected"]] : build_select($r_collected, $r_collected_d, $dis["collected"], "collected", $inputbox_style);
	$status_select=$_GET["type"]=="edit"? "<input type='hidden' name='status' value=\"$r_sale[status]\" />".$r_status_d[$r_sale["status"]] : build_select($r_status, $r_status_d, $dis["status"], "status", $inputbox_style);
	
	//get the product items from post / 1st time edit a package
	if($_GET["type"]=="add" && $post_s["__req"] && !$msg){
		$i=0;
		foreach($post_s as $f => $v){
			if(preg_match('/^e_refno_[0-9]+/', $f)){
				$pi=preg_replace('/e_refno_/', '', $f);
				$e_prods[$i]["refno"]=$v;
				$e_prods[$i]["qty"]=$post_d["e_qty_$pi"];
				$i++;
			}
		}
	}
	unset($prod_list);
	for($i=0,$t=count($e_prods);$i<$t;$i++){
		$prod_list.="
		<tr class='ppl_body' id='refno_row_$i'>
			<td><a href='#' name='del_prod' rel='$i'><img src='".M_URL."/images/icons/delete.png' /></a></td>
			<td><input type='text' name='e_refno_$i' value=\"{$e_prods[$i]['refno']}\" style='width:100%;' /></td>
			<td><input type='text' name='e_qty_$i' id=\"pq_input_$i\" value=\"{$e_prods[$i]['qty']}\" style='width:100%;' /></td>
		</tr>";
		$added_refno_js.="
		added_refno[$i] = '".addslashes($e_prods[$i]['refno'])."';";
	}
	$next_prod_entry_index=$i;

	//javascript
	ob_start();
	?>
<script type="text/javascript" src="<?php echo JS_URL."/get_file_gzip.php?file=".urlencode("jquery.js,jquery.livequery.js,jquery.datepicker.js,fn/fn_in_array.js,fn/fn_array_flip.js"); ?>"></script>
<script type="text/javascript">
var prod_index = <?php echo $next_prod_entry_index; ?>;
jQuery(document).ready(function(j){
	j('form[@name=sale_form]').submit(function(){
		j('input[@name=submit_btn]').attr('disabled','disabled');
	});

	<?php # check user ?>
	j('input#check_uid_btn').click(function(){
		j('span#user_text').html('').removeClass('red');
		if(j('input[@name=uid]').val()==''){
			j('span#user_text').html('<?php echo addslashes(__("Please provide a Member ID!")); ?>').addClass('red');
		}else{
			j(this).attr('disabled','disabled');
			j.ajax({
				url: '<?php echo "$this_file?aj=1&type=$get_s[type]".($get_s["type"]=="edit"? "&id=$get_s[id]" : "")."&check_uid=1"; ?>',
				data: {'uid': j('input[@name=uid]').val()},
				type: 'post',
				dataType: 'xml',
				error: function(){
					j('span#user_text').html('<?php echo addslashes(__("Error checking...")); ?>').addClass('red');
				},
				success: function(data){
					var mesg='';
					if(j('loggedout', data).text()=='loggedout'){
						mesg='<?php echo addslashes(__("You have been logged out.")); ?>';
					}else{
						j(data).find('msg').each(function(){
							mesg+=j(this).text()+' ';
						});
					}
					var status=j(data).find('status').text();
					j('span#user_text').html(mesg).addClass(status==1? 'bold' : 'red');
				},
				complete: function(){
					j('input#check_uid_btn').attr('disabled','');
				}
			});
		}
	});

	<?php #add new product ?>
	var added_refno = new Array();
	<?php echo $added_refno_js; ?>
	j('a[@name=add_prod]').livequery('click', function(){
		var refno = j(this).attr('rel');
		if(in_array(refno, added_refno)){
			refarr = array_flip(added_refno);
			refi = refarr[refno];
			j('input#pq_input_'+refi).val(parseInt(j('input#pq_input_'+refi).val()) + 1);
		}else{
			j('table#pprod-list').append('<tr class="ppl_body" id="refno_row_'+prod_index+'"><td><a href="#" name="del_prod" rel="'+prod_index+'"><img src="<?php echo M_URL."/images/icons/delete.png"; ?>" /></a></td><td><input type="text" name="e_refno_'+prod_index+'" value="'+refno+'" style="width:100%;" /></td><td><input type="text" name="e_qty_'+prod_index+'" id="pq_input_'+prod_index+'" value="1" style="width:100%;" /></td></tr>');
			added_refno[prod_index] = refno;
			prod_index++;
		}
		return false;
	});
	
	<?php #delete a product ?>
	j('a[@name=del_prod]').livequery('click', function(){
		var refi = j(this).attr('rel');
		j('tr#refno_row_'+refi).remove();
		added_refno[refi] = '';
		return false;
	});
	
	<?php #page nav ?>
	j('p#pml_pagelinks > a').livequery('click', function(){
		var page = j(this).text();
		var catid = j('select[@name=category_id] > option:selected').val();
		var title = j('input[@name=prod_search]').val();
		prod_search(catid, title, page);
		return false;
	});
	
	j('input[@name=prod_search]').keypress(function(e){
		if (e.which == 13) {
			j('input[@name=btn_prod_search]').click();
			return false;
		}
	});
	j('input[@name=btn_prod_search]').click(function(){
		var catid = j('select[@name=category_id] > option:selected').val();
		var title = j('input[@name=prod_search]').val();
		prod_search(catid, title, 1);
	});
	
	function prod_search(catid, title, page){
		j('div#prod_search_div').html('<?php echo addslashes(__("Searching"))."..."; ?>').removeClass('red');
		j.ajax({
			url: '<?php echo "$this_file?aj=1&type=$get_s[type]".($get_s["type"]=="edit"? "&id=$get_s[id]" : "")."&search_prod=1"; ?>',
			data: {'catid': catid, 'title': title, 'page': page},
			type: 'post',
			dataType: 'html',
			error: function(){
				j('div#prod_search_div').html('<?php echo AddSlashes(__("Error searching...")); ?>').addClass('red');
			},
			success: function(data){
				var mesg='';
				var status='';
				if(j('loggedout', data).text()=='loggedout'){
					mesg='<?php echo AddSlashes(__("You have been logged out.")); ?>';
					status=2;
				}else{
					mesg=data;
				}
				j('div#prod_search_div').html(mesg).addClass(status==2? 'red' : '');
			},
			complete: function(){
			}
		});
	}
	
	<?php # calculate product cost ?>
	j('input[@name=calc_prod_cost]').click(function(){
		j('div#prod_cost').html('<?php echo addslashes(__("Calculating"))."..."; ?>').removeClass('red');
		var ref_qs = '', qty = '', refno = '';
		for(pi in added_refno){
			if (added_refno[pi] != ''){
				qty = j('input#pq_input_'+pi).val();
				refno = j('input[@name=e_refno_'+pi+']').val();
				ref_qs += '&refno'+pi+'='+refno+'&qty'+pi+'='+qty;
			}
		}
		ref_qs += '&delivery_cost='+j('input[@name=delivery_cost]').val();
		j.ajax({
			url: '<?php echo "$this_file?aj=1&type=$get_s[type]".($get_s["type"]=="edit"? "&id=$get_s[id]" : "")."&calc_cost=1"; ?>',
			data: ref_qs,
			type: 'post',
			dataType: 'html',
			error: function(){
				j('div#prod_cost').html('<?php echo AddSlashes(__("Error calculating...")); ?>').addClass('red');
			},
			success: function(data){
				var mesg='';
				var status='';
				if(j('loggedout', data).text()=='loggedout'){
					mesg='<?php echo AddSlashes(__("You have been logged out.")); ?>';
					status=2;
				}else{
					mesg=data;
				}
				j('div#prod_cost').html(mesg).addClass(status==2? 'red' : '');
			},
			complete: function(){
			}
		});
	});
	
	<?php #datepicker ?>
	j('input[@name=_collected_date]').datepicker({
		changeMonth: true,
		changeYear: true,
		dateFormat: 'yy-mm-dd',
		minDate: new Date(2009,6,1), 
		maxDate: '+1M +10D'
	});
	j('input[@name=cdate]').datepicker({
		changeMonth: true,
		changeYear: true,
		dateFormat: 'yy-mm-dd',
		minDate: new Date(2009,6,1), 
		maxDate: '+1M +10D'
	});
	
	<?php #print invoice ?>
	j('input[@name=print_invoice]').click(function(){
		window.open('<?php echo addslashes("$this_file?print_invoice=1&type=edit&id=$get_s[id]"); ?>', 'print_window', 'status=1, toolbar=1, location=1, menubar=1, width=700, height=700');
	});
});
</script>
	<?php
	$jvscript = ob_get_clean();

	//css
	ob_start();
	?>
<link rel="stylesheet" href="<?php echo CSS_URL; ?>/jstheme/ui-lightness/jquery-ui.css" type="text/css" />
	<?php
	$css .= ob_get_contents();
	ob_end_clean();

	//back button
	$url_referer=$_SERVER["HTTP_REFERER"];
	if($post_s["back_url"]){
		$back_url=$post_s["back_url"];
	}elseif($url_referer && !strstr($url_referer, $this_file)){
		$back_url=$url_referer;
	}else{
		$back_url=$list_file;
	}

	//format input row
	if($get_s['type'] == 'add'){
		$display_fields=array("uid","_remark");
	}else{
		$display_fields=array("_collected_date","edate","cdate","_remark");
	}
	foreach($form_fields as $field => $default){
		if(in_array($field, $display_fields)){
			$db_fieldname=preg_match('/^_/', $field)? substr($field, 1) : $field;
			$dbr=explode("#", $vars["dbr"]["purchase"][$db_fieldname]);
			$readonly=$textarea=false;
			$extra_display='';
			if($field == 'uid'){
				$extra_display="<br />\n<span id='user_text'>$user_text</span><input type='button' id='check_uid_btn' value='Check Member' />";
			}
			if(in_array($field, array("_remark"))){
				$textarea=true;
			}
			if($_GET["type"]=="edit"){
				$readonly=true;
			}
			$readonly_str=$readonly? "readonly='readonly'" : "";
			$form_inputfield[$db_fieldname]="
			<tr id='".$db_fieldname."_inputrow'>
				<td width='$td_width'>".__($dbr[4]).__(":").(!$readonly && $dbr[3]=='m'? " ".__("*") : "")."</td>
				<td>".($readonly? "<input type='hidden' name='$field' value=\"$dis[$field]\" />".$dis[$field].$readonly_extra_display : ($textarea? "<textarea name='$field' rows='6' $inputbox_style $readonly_str>".$dis[$field]."</textarea>" : "
				<input type='text' name='$field' $inputbox_style value=\"".$dis[$field]."\" $readonly_str />"))."$extra_display</td>
			</tr>";
		}
	}

	//product entry row
	if($_GET["type"]=="edit"){
		$dprods=prepare_prod_for_display_from_msid($r_sale['id']);
		$formatted_prod=format_prod_display2($dprods);
		$formatted_prod = str_replace('width:600px;', 'width:100%;', $formatted_prod);
		$prod_entry_row="
		<tr id='prod_entry_inputrow'>
			<td colspan='2'>".__("Products").__(":")."</td>
		</tr>
		<tr>
			<td colspan='2'>$formatted_prod</td>
		</tr>";
	}else{
		//product search
		$cat_select = build_select($r_scat, $r_scat_d, '', 'category_id', "style='width:100%;'");
		$o_searchcat = new SearchCat($category_id = 0, $product_title = '', $cur_page = 0, $item_per_page = 10);
		$prod_search = $o_searchcat->display();

		$prod_entry_row="
		<tr id='prod_entry_inputrow'>
			<td width='$td_width'>".__("Purchase Products").__(":")." ".__("*")."</td>
			<td>".__("Browse Products").":<br />
				<table class='prod-mini-list'>
					<tr class='pml_body'>
						<td>".__("Category").":</td>
						<td><div id='div_category_search'>$cat_select</div></td>
					</tr>
					<tr class='pml_body'>
						<td>".__("Search").":</td>
						<td><input type='text' name='prod_search' value='' style='width:100%;' /></td>
					</tr>
					<tr class='pml_body'>
						<td colspan='2' class='center'><input type='button' name='btn_prod_search' value='".__("Search")."' /></td>
					</tr>
				</table><br />
				<div id='prod_search_div'>$prod_search</div>
				<p>".__("To purchase the products, browse from the product list above and click to add.")."</p>
				<table class='package-prod-list' id='pprod-list'>
					<tr class='ppl_header'>
						<td></td>
						<td>".__("Reference No.")."</td>
						<td>".__("Quantity")."</td>
					</tr>
					$prod_list
				</table>
			</td>
		</tr>";
	}
	//choose pickup location row
	if($_GET["type"]=="edit"){
		if($r_sale["stockist_sale"] == 'y'){
			$this_stockist = get_stockist_detail_by_id($r_sale['ssid']);
			$purchase_from=__("Stockist ID").__(":")." $this_stockist[sid], $this_stockist[name]<br />\n$r_sale[collect_address]".($r_sale['collect_city']? "<br />\n$r_sale[collect_city]" : '').($r_sale['collect_zip']? "<br />\n$r_sale[collect_zip], " : "").($r_sale['collect_state']? "$r_sale[collect_state]" : "")."<br />\n".$r_country_d[$r_sale["collect_country"]];
		}else{
			$purchase_from=$r_sale['mail_type'] == 'cr'? __("Courier") : __("Headquater");
		}
	}
	$purchase_from_row="
		<tr id='prod_entry_inputrow'>
			<td>".__("Pickup Location").__(":").($get_s['type'] == 'add'? " ".__("*") : '')."</td>
			<td>
				".($_GET["type"]=="edit"? $purchase_from : $purchase_from_select)."
			</td>
		</tr>";

	$member_sales=($errmsg || $msg?
	"$errmsg $msg" : "")."
	<form name='sale_form' method='post' action='$this_file?$_SERVER[QUERY_STRING]' enctype='multipart/form-data'>
	<input type='hidden' name='__req' value='1' />
	<input type='hidden' name='back_url' value=\"$back_url\" />
	<table class='pbt_table' style='width:100%'>
		<tr>
			<td colspan='2' class='center' style='padding:20px 0 20px 0;'>
			<input type='button' value='".__('Back')."' onclick=\"location='$back_url';\">&nbsp;&nbsp;&nbsp;
			".($get_s['type'] == 'add'? "<input type='submit' name='submit_btn' value=\"".__("Preview")."\" />&nbsp;&nbsp;&nbsp;" : '')."
			</td>
		</tr>
		<tr class='pbt_header'>
			<td colspan='2'>".__("Sales Information")."</td>
		</tr>
		$form_inputfield[uid]
		$prod_entry_row
		<tr>
			<td>".__("Payment Type").__(":").($get_s['type'] == 'add'? " ".__("*") : '')."</td>
			<td>$payment_channel_select</td>
		</tr>
		$form_inputfield[delivery_cost]".($get_s['type'] == 'add'? "
		<tr>
			<td>".__("Purchase Cost").__(":")."</td>
			<td><p class='center'><input type='button' name='calc_prod_cost' value=\"".__("Calculate Cost")."\" /></p>
				<div id='prod_cost'></div>
			</td>
		</tr>" : "").($get_s['type'] == 'edit'? "
		$form_inputfield[edate]
		$form_inputfield[cdate]" : '')."
		$form_inputfield[remark]".($_GET["type"]=="edit"? "
		<tr>
			<td>".__("Status").__(":")."</td>
			<td>$status_select</td>
		</tr>" : "")."
		<tr>
			<td colspan='2' class='center' style='padding:20px 0 20px 0;'>
			<input type='button' value='".__('Back')."' onclick=\"location='$back_url';\">&nbsp;&nbsp;&nbsp;
			".($get_s['type'] == 'add'? "<input type='submit' name='submit_btn' value=\"".__("Preview")."\" />&nbsp;&nbsp;&nbsp;" : '')."
			</td>
		</tr>
	</table>
	</form>";
}

$content="<h2>$page_title</h2>$member_sales";

print format_member_page($content, $this_title, $content_title, $css.$jvscript);
?>